<template>
  <view class="container">
    <!-- 用户信息区域 -->
    <view class="user-info-section">
      <block v-if="userStore.isLogin && userStore.userInfo">
        <view class="user-info">
          <image
            :src="userStore.userInfo.avatarUrl || '/static/default-avatar.png'"
            class="avatar"
            mode="aspectFill"
          />
          <view class="info">
            <text class="nickname">{{
              userStore.userInfo.nickName || "微信用户"
            }}</text>
            <text class="phone">{{ userStore.userInfo.phone || "" }}</text>
          </view>
        </view>
      </block>
      <block v-else>
        <view class="no-login-info">
          <image
            src="/static/default-avatar.png"
            class="avatar"
            mode="aspectFill"
          />
          <view class="info">
            <button
              class="login-btn"
              open-type="getPhoneNumber"
              @getphonenumber="handleGetPhoneNumber"
            >
              <text class="login-text">立即登录</text>
            </button>
          </view>
        </view>
      </block>
    </view>

    <!-- 订单区域 -->
    <view class="order-section">
      <view class="section-header" @tap="navTo('/pages/order/list')">
        <text class="title">我的订单</text>
        <view class="more">
          <text>查看全部</text>
          <uni-icons type="right" size="14" color="#999" />
        </view>
      </view>
      <view class="order-types">
        <view
          class="type-item"
          v-for="(item, index) in orderTypes"
          :key="index"
          @tap="navTo(item.url)"
        >
          <view class="icon-wrap">
            <image :src="item.icon" class="icon" mode="aspectFit" />
            <text class="badge" v-if="userStore.isLogin && item.count">{{
              item.count
            }}</text>
          </view>
          <text class="label">{{ item.label }}</text>
        </view>
      </view>
    </view>

    <!-- 功能列表 -->
    <view class="function-list">
      <view
        class="function-item"
        v-for="(item, index) in functionList"
        :key="index"
        @tap="navTo(item.url)"
      >
        <view class="left">
          <uni-icons :type="item.icon" size="20" color="#333" />
          <text class="label">{{ item.label }}</text>
        </view>
        <uni-icons type="right" size="14" color="#999" />
      </view>
    </view>

    <!-- 退出登录 -->
    <view class="logout-btn" v-if="userStore.isLogin" @tap="handleLogout">
      退出登录
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { useUserStore } from "@/store/userStore";
import { userService } from "@/services/user";
import { orderService } from "@/services/order";

// 初始化 store
const userStore = useUserStore();

// 订单类型配置
const orderTypes = ref([
  {
    label: "待付款",
    icon: "/static/order-icons/daifukuan.png",
    url: "/pages/order/list?type=unpaid",
    count: 0,
  },
  {
    label: "待发货",
    icon: "/static/order-icons/daifahuo.png",
    url: "/pages/order/list?type=unshipped",
    count: 0,
  },
  {
    label: "待收货",
    icon: "/static/order-icons/daishouhuo.png",
    url: "/pages/order/list?type=unreceived",
    count: 0,
  },
  {
    label: "已完成",
    icon: "/static/order-icons/trues.png",
    url: "/pages/order/list?type=completed",
    count: 0,
  },
]);

// 功能列表配置
const functionList = ref([
  { label: "收货地址", icon: "location", url: "/pages/address/list" },
  { label: "优惠券", icon: "ticket", url: "/pages/coupon/list" },
  { label: "我收藏", icon: "star", url: "/pages/collect/list" },
  { label: "支付记录", icon: "wallet", url: "/pages/pay/records" },
  { label: "退款记录", icon: "refresh", url: "/pages/pay/refund-list" },
  { label: "支付统计", icon: "chart", url: "/pages/pay/statistics" },
  { label: "联系客服", icon: "headphones", url: "customer-service" },
]);

// 处理获取手机号
const handleGetPhoneNumber = async (e) => {
  // 检查是否成功获取手机号
  if (e.detail.errMsg !== "getPhoneNumber:ok") {
    uni.showToast({
      title: "获取手机号失败",
      icon: "none",
    });
    return;
  }

  try {
    // 获取微信登录code
    const { code } = await uni.login({
      provider: "weixin",
    });

    uni.showLoading({
      title: "登录中...",
      mask: true,
    });

    // 调用登录接口
    const loginRes = await userStore.wxLogin({
      code,
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
    });

    if (loginRes) {
      uni.showToast({
        title: "登录成功",
        icon: "success",
      });
    }
  } catch (error) {
    console.error("登录失败:", error);
    uni.showToast({
      title: error.message || "登录失败",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
};

// 处理退出登录
const handleLogout = () => {
  uni.showModal({
    title: "提示",
    content: "确定要退出登录吗？",
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({
          title: "退出中...",
          mask: true,
        });
        try {
          const success = await userStore.logout();
          if (success) {
            // 退出成功，不需要额外处理，store中已经处理了提示和跳转
          }
        } catch (error) {
          console.error("退出失败:", error);
          uni.showToast({
            title: "退出失败",
            icon: "none",
          });
        } finally {
          uni.hideLoading();
        }
      }
    },
  });
};

// 页面导航
const navTo = (url) => {
  if (!userStore.isLogin) {
    uni.showToast({
      title: "请先登录",
      icon: "none",
    });
    return;
  }

  if (url === "customer-service") {
    // 打开客服会话
    uni.openCustomerServiceChat({
      extInfo: { url: "https://work.weixin.qq.com/..." },
      corpId: "your_corp_id",
      success: () => {},
    });
    return;
  }

  uni.navigateTo({ url });
};

// 初始化用户信息
const initUserInfo = async () => {
  if (userStore.isLogin && !userStore.userInfo) {
    await userStore.getUserInfo();
  }
};

// 获取订单数量
const fetchOrderCounts = async () => {
  if (!userStore.isLogin) return;

  // 临时禁用订单数量请求，等待后端修复
  /*
  try {
    const res = await orderService.getOrderCount();

    if (res.success) {
      orderTypes.value[0].count = res.data.unpaid || 0;
      orderTypes.value[1].count = res.data.unshipped || 0;
      orderTypes.value[2].count = res.data.unreceived || 0;
      orderTypes.value[3].count = res.data.completed || 0;
    }
  } catch (error) {
    console.error("获取订单数量失败:", error);
  }
  */
  
  // 临时设置默认值
  orderTypes.value[0].count = 0;
  orderTypes.value[1].count = 0;
  orderTypes.value[2].count = 0;
  orderTypes.value[3].count = 0;
};

onMounted(() => {
  initUserInfo();
});

// 每次显示页面时检查登录状态并更新用户信息
onShow(() => {
  if (userStore.isLogin) {
    initUserInfo();
    fetchOrderCounts();
  }
});
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 40rpx;
}

// 用户信息区域
.user-info-section {
  background: linear-gradient(180deg, #ff4444 0%, #ff6666 100%);
  padding: 40rpx 30rpx;
  color: #fff;
  position: relative;
  overflow: hidden;

  &::after {
    content: "";
    position: absolute;
    bottom: -160rpx;
    left: -20%;
    width: 140%;
    height: 240rpx;
    background: #f8f8f8;
    border-radius: 50% 50% 0 0;
    box-shadow: 0 -3rpx 12rpx rgba(0, 0, 0, 0.02);
  }

  .user-info,
  .no-login-info {
    display: flex;
    align-items: center;
    position: relative;
    z-index: 1;

    .avatar {
      width: 150rpx;
      height: 150rpx;
      border-radius: 50%;
      border: 4rpx solid rgba(255, 255, 255, 0.3);
      background-color: #fff;
    }

    .info {
      margin-left: 30rpx;

      .nickname,
      .login-text {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
      }

      .phone,
      .login-desc {
        font-size: 24rpx;
        opacity: 0.8;
      }
    }
  }

  .no-login-info {
    opacity: 0.9;
    padding: 20rpx 0;

    .avatar {
      border: none;
      background: rgba(255, 255, 255, 0.15);
    }

    .info {
      display: flex;
      flex-direction: column;
      align-items: center;

      .login-btn {
        margin: 0;
        padding: 0;
        background: rgba(255, 255, 255, 0.95);
        border: none;
        line-height: normal;

        &::after {
          border: none;
        }

        .login-text {
          font-size: 32rpx;
          font-weight: 500;
          margin: 0;
          color: #ff4444;
          margin-bottom: 4rpx;
        }
      }

      .login-desc {
        color: #999;
        font-size: 20rpx;
      }
    }

    &:active {
      .login-btn {
        transform: scale(0.98);
        opacity: 0.9;
      }
    }
  }
}

// 订单区域
.order-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20rpx;
    border-bottom: 2rpx solid #f5f5f5;

    .title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
    }

    .more {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #999;
    }
  }

  .order-types {
    display: flex;
    padding: 30rpx 0 10rpx;

    .type-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;

      .icon-wrap {
        position: relative;
        margin-bottom: 16rpx;

        .icon {
          width: 48rpx;
          height: 48rpx;
        }

        .badge {
          position: absolute;
          top: -10rpx;
          right: -10rpx;
          background-color: #ff4444;
          color: #fff;
          font-size: 20rpx;
          padding: 0 8rpx;
          border-radius: 20rpx;
          min-width: 32rpx;
          text-align: center;
        }
      }

      .label {
        font-size: 24rpx;
        color: #333;
      }
    }
  }
}

// 功能列表
.function-list {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  .function-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 20rpx;
    border-bottom: 2rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .left {
      display: flex;
      align-items: center;

      .label {
        font-size: 28rpx;
        color: #333;
        margin-left: 20rpx;
      }
    }
  }
}

// 退出登录按钮
.logout-btn {
  margin: 40rpx 20rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background-color: #fff;
  border-radius: 44rpx;
  font-size: 28rpx;
  color: #ff4444;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  &:active {
    opacity: 0.8;
  }
}
</style>
